<script lang="ts" setup>
import { getRuleListAPI, addRuleAPI, deleteRuleAPI, getRuleAPI, editRuleAPI } from '@/apis/car';
import type { Rule, RuleListParams, AddRuleParams } from '@/types/car';
import { ref } from 'vue';
import { utils, writeFileXLSX } from 'xlsx';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'

const ruleList = ref<Rule[]>([])
const  params=ref<RuleListParams>({page:1,pageSize:10})
  const total = ref(0)

// 获取计费规则列表
const getRuleList = async () => {
  const res = await getRuleListAPI(params.value)
  ruleList.value = res.data.rows
  total.value = res.data.total
}
getRuleList()

// 计费方式
// 计费规则
const chargeTypeMap = new Map<Rule['chargeType'], string>([
  // [key, value] 键值对
  ['duration', '时长收费'],
  ['turn', '按次收费'],
  ['partition', '分段消费']
]);
// 导出计费规则
const exportToExcel = ()=>{
  // 1. 创建工作簿（xlsx文件）
  const workbook = utils.book_new()
  // 2. 创建工作表 (json转工作表)
  const worksheet = utils.json_to_sheet(
    [
      { name: '张三', age: 18 },
      { name: '李四', age: 28 }
    ]
  )
  // 3. 在 xlsx 文件中添加 工作表, Data 为工作表名称
  utils.book_append_sheet(workbook, worksheet, 'Data')
  // 4. 覆盖默认表头 (工作表, 二维数组, 表头坐标)
  utils.sheet_add_aoa(worksheet, [['姓名', '年龄']], { origin: 'A1' })
  // 4. 导入下载 xlsx 文件
  writeFileXLSX(workbook, '计费规则表.xlsx')
}

// 弹窗显示控制
const dialogVisible = ref(false)

// 表单数据
const ruleForm = ref<AddRuleParams>({
  ruleNumber: '',
  ruleName: '',
  chargeType: 'duration',
  freeDuration: 0,
  chargeCeiling: 0,
  durationPrice: 0,
  durationTime: 0,
  durationType: 'minute',
  turnPrice: 0,
  partitionFrameTime: 0,
  partitionFramePrice: 0,
  partitionIncreaseTime: 0,
  partitionIncreasePrice: 0
})

// 表单ref
const formRef = ref<FormInstance>()

// 表单验证规则
const rules = ref<FormRules<AddRuleParams>>({
  ruleNumber: [
    { required: true, message: '请输入计费规则编号', trigger: 'blur' }
  ],
  ruleName: [
    { required: true, message: '请输入计费规则名称', trigger: 'blur' }
  ],
  chargeType: [
    { required: true, message: '请选择计费方式', trigger: 'change' }
  ],
  // 时长收费必填项
  durationTime: [
    { 
      required: true, 
      message: '请输入单位时间', 
      trigger: 'blur',
      // 仅在时长收费时验证
      validator: (_, value, callback) => {
        if (ruleForm.value.chargeType === 'duration' && !value) {
          callback(new Error('请输入单位时间'))
        } else {
          callback()
        }
      }
    }
  ],
  durationPrice: [
    {
      required: true,
      message: '请输入单价',
      trigger: 'blur',
      validator: (_, value, callback) => {
        if (ruleForm.value.chargeType === 'duration' && !value) {
          callback(new Error('请输入单价'))
        } else {
          callback()
        }
      }
    }
  ],
  // 按次收费必填项
  turnPrice: [
    {
      required: true,
      message: '请输入每次价格',
      trigger: 'blur',
      validator: (_, value, callback) => {
        if (ruleForm.value.chargeType === 'turn' && !value) {
          callback(new Error('请输入每次价格'))
        } else {
          callback()
        }
      }
    }
  ],
  // 分段收费必填项
  partitionFrameTime: [
    {
      required: true,
      message: '请输入段内时间',
      trigger: 'blur',
      validator: (_, value, callback) => {
        if (ruleForm.value.chargeType === 'partition' && !value) {
          callback(new Error('请输入段内时间'))
        } else {
          callback()
        }
      }
    }
  ],
  partitionFramePrice: [
    {
      required: true,
      message: '请输入段内费用',
      trigger: 'blur',
      validator: (_, value, callback) => {
        if (ruleForm.value.chargeType === 'partition' && !value) {
          callback(new Error('请输入段内费用'))
        } else {
          callback()
        }
      }
    }
  ]
})

// 添加一个 ref 存储当前编辑的规则 ID
const editId = ref<number>()

// 修改 editRule 函数，保存编辑 ID
const editRule = async (id: number) => {
  const res = await getRuleAPI(id)
  dialogVisible.value = true
  editId.value = id  // 保存编辑 ID
  ruleForm.value = { ...res.data }
}

// 修改 addRule 函数，清除编辑 ID
const addRule = () => {
  dialogVisible.value = true
  editId.value = undefined  // 清除编辑 ID
  // 清空表单
  formRef.value?.resetFields()
}

// 提交表单
const onSubmit = async () => {
  try {
    await formRef.value?.validate()
    
    const submitData = {
      ...ruleForm.value,
      id: editId.value
    }

    if (editId.value) {
      // 编辑模式
      await editRuleAPI(submitData as Rule)
      ElMessage.success('编辑成功')
      // 清空表单数据
      formRef.value?.resetFields()
      ruleForm.value = {
        ruleNumber: '',
        ruleName: '',
        chargeType: 'duration',
        freeDuration: 0,
        chargeCeiling: 0,
        durationPrice: 0,
        durationTime: 0,
        durationType: 'minute',
        turnPrice: 0,
        partitionFrameTime: 0,
        partitionFramePrice: 0,
        partitionIncreaseTime: 0,
        partitionIncreasePrice: 0
      }
    } else {
      // 添加模式
      await addRuleAPI(submitData)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    getRuleList()
  } catch (e) {
    console.error(e)
    ElMessage.error(editId.value ? '编辑失败' : '添加失败')
  }
}

// 删除计费规则
const deleteRule = async (id: number) => {
  //二次确定弹窗 
  ElMessageBox.confirm(
    '删除计费规则不可撤回，是否确认删除当前计费规则?',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    
    await deleteRuleAPI(id)
    ElMessage.success('删除成功')
    // 刷新页面
    getRuleList()
  })
}
</script>

<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="addRule">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上限(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <template #default="{ row }">
            {{ chargeTypeMap.get(row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" width="320" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="editRule(row.id)">编辑</el-button>
            <el-button size="small" type="primary" link @click="deleteRule(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加规则弹窗 -->
    <el-dialog v-model="dialogVisible" title="添加计费规则" width="600px">
      <el-form 
        ref="formRef"
        :model="ruleForm" 
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="计费规则编号" required>
          <el-input v-model="ruleForm.ruleNumber" placeholder="请输入计费规则编号"/>
        </el-form-item>
        
        <el-form-item label="计费规则名称" required>
          <el-input v-model="ruleForm.ruleName" placeholder="请输入计费规则名称"/>
        </el-form-item>

        <el-form-item label="计费方式" required>
          <el-radio-group v-model="ruleForm.chargeType">
            <el-radio label="duration">时长收费</el-radio>
            <el-radio label="turn">按次收费</el-radio>
            <el-radio label="partition">分段收费</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="免费时长(分钟)">
          <el-input-number v-model="ruleForm.freeDuration" :min="0"/>
        </el-form-item>

        <el-form-item label="收费上限(元)">
          <el-input-number v-model="ruleForm.chargeCeiling" :min="0"/>
        </el-form-item>

        <!-- 时长收费表单项 -->
        <template v-if="ruleForm.chargeType === 'duration'">
          <el-form-item label="计时方式">
            <el-radio-group v-model="ruleForm.durationType">
              <el-radio label="minute">分钟</el-radio>
              <el-radio label="hour">小时</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="单位时间">
            <el-input-number v-model="ruleForm.durationTime" :min="0"/>
          </el-form-item>
          <el-form-item label="单价(元)">
            <el-input-number v-model="ruleForm.durationPrice" :min="0"/>
          </el-form-item>
        </template>

        <!-- 按次收费表单项 -->
        <template v-if="ruleForm.chargeType === 'turn'">
          <el-form-item label="每次价格(元)">
            <el-input-number v-model="ruleForm.turnPrice" :min="0"/>
          </el-form-item>
        </template>

        <!-- 分段收费表单项 -->
        <template v-if="ruleForm.chargeType === 'partition'">
          <el-form-item label="段内时间">
            <el-input-number v-model="ruleForm.partitionFrameTime" :min="0"/>
          </el-form-item>
          <el-form-item label="段内费用">
            <el-input-number v-model="ruleForm.partitionFramePrice" :min="0"/>
          </el-form-item>
          <el-form-item label="超出时间">
            <el-input-number v-model="ruleForm.partitionIncreaseTime" :min="0"/>
          </el-form-item>
          <el-form-item label="超出费用">
            <el-input-number v-model="ruleForm.partitionIncreasePrice" :min="0"/>
          </el-form-item>
        </template>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.rules .el-form-item {
  padding: 0 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>